<!DOCTYPE html>
<html>
  <head>
    
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Chat UI</title>
    <style>
    a {
        color: #4CAF50; /* 绿色 */
      }
    body {
        background-color: #333;
        color: #eee;
        margin: 0;
    }
      #chat-window {
        border: none;
        
        max-width: 1000px;
            margin: 0 auto;
            min-height:calc(100vh - 255px);
            height: calc(100vh - 180px);
            overflow-y: scroll;
            padding: 5px;
        }
        #chat-window::-webkit-scrollbar {
        width: 0px;
      }
      .message {
        margin: 10px;
        padding: 10px;
        border-radius: 5px;
        display: flex;
        align-items: center;
        max-width: 80%;
      }
      .user-icon {
        background-color: #102133;
        color: #fff;
        font-size: 20px;
        width: 30px;
        height: 30px;
        border-radius: 20%;
        display: flex;
        align-items: center;
        justify-content: center;
        margin-left: 10px;
      }
      .user-message {
        background-color: #333;
        color: #ccc;
        /* text-align: right; */
        margin-top: 10px;
        /* margin-right: 10px; */
        white-space: pre-wrap;
        margin-bottom: 10px;
        font-size: 20px;
        padding: 10px;
        border-radius: 8px;
      }
      .assistant-message {
        font-size: 20px;
        background-color: rgb(87, 85, 85);
        /* margin-top: 10px; */
        /* margin-bottom: 10px; */
        white-space: pre-wrap;
        color: #ccc;
        padding: 0px 10px;
        padding-bottom: 10px;
        border-radius: 8px;
      }
      .assistant-image {
        width: 30px;
        height: 30px;
        border-radius: 30%;
        margin-left: 10px;
        margin-top: 20px;
        /* margin-bottom: 10px; */
      }
      .user-image{
        width: 30px;
        height: 30px;
        border-radius: 30%;
        margin-left: 10px;
        margin-top: 10px;
        /* margin-bottom: 10px; */
      }
      .draw-image {
        max-width: 100%;
        height: auto;
        width: 1024;
        padding-top:10px;
        border-radius: 10%;
        position: relative;
      }

      .draw-image img {
        position: absolute;
        top: 50%;
        left: 50%;
        transform: translate(-50%, -50%);
      }


      .error-message {
        font-size: 30px;
        font-style: italic;
        background-color: rgb(87, 85, 85);
        margin-top: 10px;
        margin-bottom: 10px;
        margin-left: 10px;
        border-radius: 8px;
      }
    #message-container {
        display: flex;
        flex-direction: column; /* 垂直排列 */
        align-items: center; /* 居中对齐 */
        width: 100%;
    }
    textarea:focus, input:focus{
        outline: none;
    }

    #message-input {
      background-color: rgb(186, 186, 186);
      max-width: 1000px;  
        /* flex: 1; 自适应高度 */
        max-height: 180px; /* 移动端高度 */
        width: 100%;
        margin: 0;
        padding: 0;
        border: none;
        resize: vertical;
        padding:10px,10px;
        border: 10px solid transparent;
        font-size: 20px;
        height: 140px;
        /* min-height: 205px; */
        display: inline-block; /* Display the input box and submit button inline */
        vertical-align: bottom; /* Align them to the bottom */
        padding-left: 5px;
        box-sizing: border-box; /* 让 padding 不会撑开文本框 */
    }
    #message-input::-webkit-scrollbar {
        width: 0px;
      }

    #submit {
      max-width: 1000px;
        width: 100%;
        margin: 0;
        padding: 0;
        border: none;
        max-height: 40px; /* adjust this value to set the minimum height of the textarea */
        min-height: 28px; /* adjust this value to set the minimum height of the textarea */
        color: rgb(43, 107, 0);
        background-color: rgb(186, 186, 186);
        font-size: 16px;
        text-align: right;
        /* display: none; 在PC端时隐藏发送按钮 */
    }
    .floating-btn {
      position: fixed;
      top: 20px;
      right: 20px;
      background-color: #07192c;
      color: #fff;
      padding: 5px 5px;
      border-radius: 5px;
      cursor: pointer;
    }

    .child-btn {
      background-color: rgb(99, 103, 105);
      color: #ffffff;
      padding: 8px;
      border-radius: 4px;
      cursor: pointer;
      display: block;
      margin: 4px;
      font-family: 'Open Sans', sans-serif;
      font-size: 16px;
      font-weight: 600;
      text-align: center;
      border: 2px solid #797e84;
      transition: all 0.3s ease-in-out;
    }

    .child-btn:hover {
      background-color: #007bff;
      color: #fff;
    }

    .expand-text {
      display: inline;
    }



    @media screen and (max-width: 768px) {
      
        #chat-window {
            border: 1px solid black;
            min-height:calc(100vh - 210px);
            height: calc(100vh - 150px);
            overflow-y: scroll;
            padding: 5px;
        }
        #message-container {
            flex-direction: row; /* 水平排列 */
        }

        #message-input:placeholder-shown + #submit {
            display: None; /* 输入框没有焦点且没有占位符时隐藏按钮 */
        }
        #message-input::placeholder{
          content: "请输入内容，回车键换行";
        }
        #message-input:placeholder-shown{
          width: 100%;
          margin-right:0;
        }
        #message-input {
            max-height: 150px; /* 移动端高度 */
            height: 130px; 
            margin-right: 2%; 
            padding:3px 15px;
            border: 5px solid transparent;
            border-radius: 3px;
            background-color:rgb(255, 255, 255);
            width: 85%; /* 在移动端设置更小的宽度，留更多空间给发送按钮 */
            overflow-y: auto; /* 添加自动滚动 */
        }
        #message-input:focus {
          outline: none; /* 去除 focus 时的默认样式 */
        }
        #submit {
            margin-top: 0; /* 移动端无间距 */
            width: 13%;
            border-radius: 5px;
            color:rgb(255, 255, 255);
            background-color: #4CAF50;
            min-height: 34px; /* 移动端高度 */
            text-align: center;
            line-height: 34px; /* 让按钮中的文字垂直居中 */
            display: inline-block; /* 显示发送按钮 */
        }
    }
      table {
        border-collapse: collapse;
        margin-bottom: 20px;
        width: 100%;
      }

      th,
      td {
        padding: 12px 15px;
        text-align: left;
        border: 1px solid #ccc;
      }

      th {
        background-color: #1f1a1a;
      }

    </style>
    
    <script src="https://cdnjs.cloudflare.com/ajax/libs/showdown/1.9.1/showdown.min.js"></script>
    
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/prism/1.24.1/themes/prism-okaidia.min.css" />
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/prism/1.24.1/plugins/copy-to-clipboard/prism-copy-to-clipboard.min.css" />
    <script src="https://cdnjs.cloudflare.com/ajax/libs/prism/1.24.1/plugins/autoloader/prism-autoloader.min.js"></script>
    
    <script src="https://cdnjs.cloudflare.com/ajax/libs/prism/1.24.1/prism.min.js"></script>
    <!-- 引入所需的语言扩展文件 -->
    <script src="https://cdnjs.cloudflare.com/ajax/libs/prism/1.24.1/components/prism-javascript.min.js"></script>  
    <script src="https://cdnjs.cloudflare.com/ajax/libs/prism/1.24.1/components/prism-c.min.js"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/prism/1.24.1/components/prism-cpp.min.js"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/prism/1.24.1/components/prism-python.min.js"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/prism/1.24.1/components/prism-r.min.js"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/prism/1.24.1/components/prism-java.min.js"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/prism/1.24.1/components/prism-swift.min.js"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/prism/1.24.1/components/prism-matlab.min.js"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/prism/1.24.1/components/prism-go.min.js"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/clipboard.js/2.0.8/clipboard.min.js"></script>
  </head>
  <body>
    <div id="chat-window">
    </div>
    <div id="message-container">
      <textarea id="message-input" placeholder="在这里输入消息，Enter键换行，Ctrl+Enter发送"></textarea>
      <buttton id="submit"> &nbsp发送&nbsp </button>
  </div>
  <div class="floating-btn"><span class="expand-text">三</span></div>

    <script>

      const messageInput = document.getElementById('message-input');
      const mediaQuery = window.matchMedia('(max-width: 768px)');
      const chatWindow = document.getElementById('chat-window');

      var button = document.getElementById("submit");

      function handleInput() {
        // 处理输入事件
        this.style.height = 'auto';  // 重置高度
        this.style.height = this.scrollHeight + 'px';  // 调整高度
        chatWindow.style.height = 'auto';
        chatWindow.style.height = 'calc(100vh - ' + this.style.height + ' - 20px)';
        chatWindow.scrollTop = chatWindow.scrollHeight;
      }
      function addcolor_width() {
        messageInput.style.backgroundColor = "white";
        button.style.backgroundColor = "white";
      }

      function blur_width() {
        messageInput.style.backgroundColor = "rgb(186, 186, 186)";
        button.style.backgroundColor = "rgb(186, 186, 186)";
      }

      function handleMediaChange(e) {
        if (e.matches) {
          messageInput.placeholder = '在这里输入消息，Enter键换行';
          messageInput.addEventListener('input', handleInput);
          messageInput.removeEventListener('focus', addcolor_width);
          messageInput.removeEventListener('blur', blur_width);
        } else {
          messageInput.placeholder = '在这里输入消息，Enter键换行，Ctrl+Enter发送';
          messageInput.removeEventListener('input', handleInput);
          messageInput.addEventListener('focus', addcolor_width);
          messageInput.addEventListener('blur', blur_width);
        }
      }

      mediaQuery.addListener(handleMediaChange);
      handleMediaChange(mediaQuery);

      function displayintroduction(){
        const messageElement = document.createElement('div');
        messageElement.classList.add('assistant-message');
        const assistantImageElement = document.createElement('img');
        assistantImageElement.src = "{{ url_for('static', path='/icon-robot.jpg') }}";
        assistantImageElement.alt = 'Robot Image';
        assistantImageElement.classList.add('assistant-image');
        const contentElement = document.createElement('div');
        contentElement.classList.add('assistant-message');
        contentElement.innerHTML = "(3.5 stable version)我叫许三多，可以通过对话来服务。<br><br>"+
        "您可以这样与我互动：<br>"+
        "<br>" +

        "   1. 提问：<br>"+
        "     \"孕妇感到恶心，丈夫能做些什么？\"<br>" +
        "     \"请以初中三年级能理解的方式解释量子计算\"<br>" +
        "<br>"+
        "   2. 联网搜索，请在开头加上“你帮我找”四个字：<br>" +
        "     \"你帮我找 流浪地球2\"<br>" +
        
        "<br>"+
        "   3. 图片生成，请在开头加上“你帮我画”四个字：<br>" +
        "     \"你帮我画 一只虎背熊腰的神兽，3D，高清，大师级作品\"<br>" +
        "     <a href='https://gitee.com/xu-zhanwei/chatanywhere/blob/master/image_example.md'>点击此处查看精美作画指南</a><br>" +
        
        "<br>"+
        "我所提供的信息可能有事实性的错误，请一定要有自己的判断！<br><br><a href='https://gitee.com/xu-zhanwei/chatanywhere/blob/master/Support.md'>点击此处支持项目后续开发</a>" ;
        messageElement.appendChild(assistantImageElement);
        messageElement.appendChild(contentElement);
        chatWindow.appendChild(messageElement);
        
        const errorMessageElement = document.createElement('div');
        errorMessageElement.classList.add('error-message');
        errorMessageElement.innerHTML = "";
        chatWindow.appendChild(errorMessageElement);
      }
        displayintroduction();
        let messages = [];
        let messages_send = [];
        // Get the messages from LocalStorage (if they exist)
        const storedMessages = localStorage.getItem('chatMessages');
        messages = storedMessages ? JSON.parse(storedMessages) : [];
        // Get the messages from LocalStorage (if they exist)
        const sendMessages = localStorage.getItem('sendMessages');
        messages_send = sendMessages ? JSON.parse(sendMessages) : [];
        function displayassistantmessage(message){
          
          const iconElement = document.createElement('img');
          iconElement.classList.add('assistant-image');
          iconElement.src = "{{ url_for('static', path='/icon-robot.jpg') }}";
          iconElement.alt = 'Robot Image';
          const messageElement = document.createElement('div');
          messageElement.classList.add('assistant-message');
          messageElement.appendChild(iconElement);
          chatWindow.appendChild(messageElement);
          // Create a single element to display the received text
          const contentElement = document.createElement('div');
          contentElement.classList.add('assistant-message');
          messageElement.appendChild(contentElement);

          var converter = new showdown.Converter({tables: true});
          var html = converter.makeHtml(message);
          contentElement.innerHTML = html //buffer.replace(/(\r\n|\n|\r)/gm, "<br>");
          Prism.highlightAll();

          const preCodes = contentElement.getElementsByTagName('pre')
          const codeBlocks = []
          const copyButtons = []
          for (let code of preCodes) {
            // 给每个pre标签添加ID
            const id = Math.random().toString(36).slice(2)
            code.id = id

            // 添加复制按钮
            const copyButton = document.createElement('button')
            copyButton.innerText = '复制'
            copyButton.setAttribute('class', 'copy-button')
            code.parentNode.insertBefore(copyButton, code.nextSibling)
            copyButtons.push(copyButton)
            codeBlocks.push(code)
            // 给复制按钮添加复制回调函数
            const clipboard = new ClipboardJS(copyButton, {
              text: function () {
                const currentIndex = copyButtons.indexOf(copyButton)
                return codeBlocks[currentIndex].innerText
              }
            })
            clipboard.on(`success`, function () {
              copyButton.innerText = '复制成功！'
              setTimeout(() => {
                copyButton.innerText = '复制'
              }, 1500)
            })
          }
        }
        function displayusermessage(message){
            const messageElement = document.createElement('div');
            messageElement.classList.add('user-message');
            const userImageElement = document.createElement('img');
            userImageElement.src = "{{ url_for('static', path='/icon-human.jpg') }}";
            userImageElement.alt = 'User Image';
            userImageElement.classList.add('user-image');
            const contentElement = document.createElement('div');
            contentElement.classList.add('user-message');
            contentElement.innerHTML = message.replace(/(\r\n|\n|\r)/gm, "<br>");
            messageElement.appendChild(userImageElement);
            messageElement.appendChild(contentElement);
            chatWindow.appendChild(messageElement);
        }
        function displayMessages() {

          // Loop over each message in the messages list and display it in the chat window
          for (let i = 0; i < messages.length; i++) {
            const message = messages[i];
            console.log(message);
            if (message.role == 'assistant') {
              displayassistantmessage(message.content);
            } else {
              displayusermessage(message.content);
            } 
        }
      }
        displayMessages();
        
      // 获取父按钮和子按钮
      var parentBtn = document.querySelector('.floating-btn');
      var copyBtn = document.createElement('div');
      var deleteBtn = document.createElement('div');
      var expandText = document.querySelector('.expand-text');

      // 设置子按钮文本和样式
      copyBtn.innerHTML = '全部复制';
      copyBtn.classList.add('child-btn');
      deleteBtn.innerHTML = '一键删除';
      deleteBtn.classList.add('child-btn');
      
      // 创建函数以删除子按钮和恢复父按钮
      function removeChildButtons() {
        copyBtn.remove();
        deleteBtn.remove();
        document.removeEventListener('click', removeChildButtons);
        expandText.style.display = "block";
      }
      // 当单击父按钮时，显示子按钮
      parentBtn.addEventListener('click', function() {
        // 防止单击子按钮时删除子按钮
        event.stopPropagation();
        parentBtn.appendChild(copyBtn);
        parentBtn.appendChild(deleteBtn);
        // 隐藏展开的文本
        expandText.style.display = "none";

        // 在单击文档的任何其他区域时，删除子按钮并恢复父按钮
        document.addEventListener('click', removeChildButtons);
      });

      // 当单击复制按钮时，执行复制操作
      // copyBtn.addEventListener('click', function() {
      //   /* 执行复制操作的代码 */
      //   // 获取localStorage中的数据
      //   const storedMessages = localStorage.getItem('chatMessages');
      //   // 将数据转换为可复制的格式
      //   const messages = storedMessages ? JSON.parse(storedMessages) : [];
      //   var copyText = "";
      //   for (let i = 0; i < messages.length; i++) {
      //     const message = messages[i];
      //     if (message.role == 'assistant') {
      //       copyText += "AI:"+message.content+"\r\n";
      //     } else {
      //       copyText += "用户:"+message.content+"\r\n";
      //     }
      //   }
        
        const clipboard = new ClipboardJS(copyBtn, {
                  text: function () {
                    
                    // 获取localStorage中的数据
                    const storedMessages = localStorage.getItem('chatMessages');
                    // 将数据转换为可复制的格式
                    const messages = storedMessages ? JSON.parse(storedMessages) : [];
                    var copyText = "";
                    for (let i = 0; i < messages.length; i++) {
                      const message = messages[i];
                      if (message.role == 'assistant') {
                        copyText += "AI:"+message.content+"\r\n";
                      } else {
                        copyText += "用户:"+message.content+"\r\n";
                      }
                    }
                    return copyText;
                  }
                })
        
        clipboard.on(`success`, function () {
          // 改变“一键复制”为“已复制”
          copyBtn.innerHTML = '已复制';
          
          setTimeout(() => {
            copyBtn.innerText = '全部复制'
          }, 1500)
        })

      // 当单击删除按钮时，执行删除操作
      deleteBtn.addEventListener('click', function() {
        /* 执行删除操作的代码 */
        localStorage.clear();
        console.log(localStorage.getItem('chatMessages'));
        // 删除所有窗口中的内容
        chatWindow.innerHTML = "";
        displayintroduction();
        messages = [];
        messages_send = [];
      });
        chatWindow.scrollTop = chatWindow.scrollHeight;
      messageInput.addEventListener("keydown", function(event) {
        if (event.keyCode === 13 && event.ctrlKey) { // Enter key without Ctrl
          event.preventDefault(); // Prevent form submission
          sendMessage();
        } else if (event.keyCode === 13 && !event.ctrlKey) { // Ctrl + Enter
          messageInput.value += "";
        }
      });
      button.addEventListener("click", function() {
        sendMessage();
      });
      
      function disableInput() {
        messageInput.disabled = true;
        document.getElementById("submit").disabled = true;
      }

      function enableInput() {
        messageInput.disabled = false;
        document.getElementById("submit").disabled = false;
      }
      
      let timerId = null;

      function setTimer() {
        timerId = setTimeout(() => {
        const errorMessage = '糟糕！我的回答好像中断了！你可以重新问一遍吗？如果还是不行，那么请刷新此页面并检查下网络连接是否顺畅。';
        messages_send.push({"role": "assistant", "content": errorMessage});
        messages.push({"role": "assistant", "content": errorMessage});
        const errorMessageElement = document.createElement('div');
        errorMessageElement.classList.add('error-message');
        errorMessageElement.textContent = errorMessage;
        chatWindow.appendChild(errorMessageElement);
        chatWindow.scrollTop = chatWindow.scrollHeight;
        enableInput();
        }, 30000);
        }
      function resetTimer() {
        clearTimeout(timerId);
        setTimer();
      }
      function sendMessage() {
        
        disableInput();
        const message = messageInput.value;
        if (message.trim() === '') {
          enableInput();
          return;
        }
        messageInput.value = '';
        messages_send.push({"role": "user", "content": message});
        messages.push({"role": "user", "content": message});
        const messageElement = document.createElement('div');
        messageElement.classList.add('user-message');
        const iconElement = document.createElement('img');
        iconElement.classList.add('user-image');
        iconElement.src ="{{ url_for('static', path='/icon-human.jpg') }}";
        iconElement.alt = 'User Image';
        const contentElement = document.createElement('div');
        contentElement.classList.add('user-message');
        contentElement.innerHTML = message.replace(/(\r\n|\n|\r)/gm, "<br>");;
        messageElement.appendChild(iconElement);
        messageElement.appendChild(contentElement);
        chatWindow.appendChild(messageElement);
        chatWindow.scrollTop = chatWindow.scrollHeight;
        

        
          if (message.startsWith("你帮我画") ){
            
            fetch('/draw', {
              method: 'POST',
              headers: {
                'Content-Type': 'application/json'
              },
              body: JSON.stringify({"message": message}),
              timeout: 10000,
            })
            .then(response => {
              return response.json();
            })
            .then (data => {
              
            // Display the assistant icon
            const iconElement = document.createElement('img');
            iconElement.classList.add('assistant-image');
            iconElement.src = "{{ url_for('static', path='/icon-robot.jpg') }}";
            if (data.url.startsWith("http")){
              
              iconElement.alt = 'Robot Image';
              const messageElement = document.createElement('div');
              messageElement.classList.add('assistant-message');
              messageElement.appendChild(iconElement);
              chatWindow.appendChild(messageElement);
              const lineElement = document.createElement('div');
              const drawElement = document.createElement('img');
              drawElement.classList.add('draw-image');
              drawElement.src = data.url;
              drawElement.alt = 'Draw Image';
              messageElement.appendChild(lineElement);
              messageElement.appendChild(drawElement);
            }
            else{
              
              iconElement.alt = 'Robot Image';
              const messageElement = document.createElement('div');
              messageElement.classList.add('assistant-message');
              messageElement.appendChild(iconElement);
              chatWindow.appendChild(messageElement);
              messageElement.innerHTML = data.url;
              chatWindow.scrollTop = chatWindow.scrollHeight;
            }
            enableInput();
            
            function handleMediaChange2(e) {
                if (e.matches) {
                  
                  messageInput.blur();
                  messageInput.style.height = "auto";
                  messageInput.style.height = "130px";
                  chatWindow.style.height = "calc(100vh - 130px)";
                } else {
                  messageInput.focus();
                }
              }
              
              mediaQuery.addListener(handleMediaChange2);
              handleMediaChange2(mediaQuery);
            
              messages_send.push({"role": "assistant", "content": "已为您生成图片。"});
              
                messages.push({"role": "assistant", "content": message});
            })
            .catch(error => {
              const errorMessage = document.createElement('div');
              errorMessage.classList.add('error-message');
              errorMessage.textContent = '连接已断开，请检查网络连接后重新尝试。或者您的描述我不能给您画出';
              clearTimeout(timerId);
              chatWindow.appendChild(errorMessage);
              chatWindow.scrollTop = chatWindow.scrollHeight;
              enableInput();
              
              function handleMediaChange2(e) {
                      if (e.matches) {
                        
                        messageInput.blur();
                        messageInput.style.height = "auto";
                        messageInput.style.height = "130px";
                        chatWindow.style.height = "calc(100vh - 130px)";
                      } else {
                        messageInput.focus();
                      }
                    }
                    
                mediaQuery.addListener(handleMediaChange2);
                handleMediaChange2(mediaQuery);
              });
          }else{
        setTimer();
        // Send a POST request to the server
        fetch('/message', {
          method: 'POST',
          headers: {
            'Content-Type': 'application/json'
          },
          body: JSON.stringify({"message": messages_send}),
          timeout: 10000,
        })
        .then(response => {
          // Display the assistant icon
          const iconElement = document.createElement('img');
          iconElement.classList.add('assistant-image');
          iconElement.src = "{{ url_for('static', path='/icon-robot.jpg') }}";
          iconElement.alt = 'Robot Image';
          const messageElement = document.createElement('div');
          messageElement.classList.add('assistant-message');
          messageElement.appendChild(iconElement);
          chatWindow.appendChild(messageElement);
          // Create a single element to display the received text
          const contentElement = document.createElement('div');
          contentElement.classList.add('assistant-message');
          messageElement.appendChild(contentElement);
          // Start reading the response stream
          const reader = response.body.getReader();
          let buffer = '';
          reader.read().then(function processText({ done, value }) {
            if (done) {
              
              var converter = new showdown.Converter({tables: true});
              var html = converter.makeHtml(buffer);
              contentElement.innerHTML = html //buffer.replace(/(\r\n|\n|\r)/gm, "<br>");
              Prism.highlightAll();

              const preCodes = contentElement.getElementsByTagName('pre')
              const codeBlocks = []
              const copyButtons = []
              for (let code of preCodes) {
                // 给每个pre标签添加ID
                const id = Math.random().toString(36).slice(2)
                code.id = id

                // 添加复制按钮
                const copyButton = document.createElement('button')
                copyButton.innerText = '复制'
                copyButton.setAttribute('class', 'copy-button')
                code.parentNode.insertBefore(copyButton, code.nextSibling)
                copyButtons.push(copyButton)
                codeBlocks.push(code)
                // 给复制按钮添加复制回调函数
                const clipboard = new ClipboardJS(copyButton, {
                  text: function () {
                    const currentIndex = copyButtons.indexOf(copyButton)
                    return codeBlocks[currentIndex].innerText
                  }
                })
                clipboard.on(`success`, function () {
                  copyButton.innerText = '复制成功！'
                  setTimeout(() => {
                    copyButton.innerText = '复制'
                  }, 1500)
                })
              }
              // if the buffer is start with "请让我先总结下我们上面的对话"
              // if (buffer.startsWith("请让我先总结下我们上面的对话")) {
              //   messages_send = [];
              //   buffer = buffer.replace("请让我先总结下我们上面的对话", "")
              // }
              messages_send.push({"role": "assistant", "content": buffer});
              messages.push({"role": "assistant", "content": buffer});
              if (messages_send.length >6) {
                messages_send.shift();
                messages_send.shift();
              }
              chatWindow.scrollTop = chatWindow.scrollHeight;
              clearTimeout(timerId);
              enableInput();
              
              function handleMediaChange2(e) {
                if (e.matches) {
                  
                  messageInput.blur();
                  messageInput.style.height = "auto";
                  messageInput.style.height = "130px";
                  chatWindow.style.height = "calc(100vh - 130px)";
                } else {
                  messageInput.focus();
                }
              }
              
              mediaQuery.addListener(handleMediaChange2);
              handleMediaChange2(mediaQuery);
              localStorage.setItem('chatMessages', JSON.stringify(messages));
              localStorage.setItem('sendMessages', JSON.stringify(messages_send));
              return;
            }

            // Add the received chunk to the buffer and display the current content
            text = new TextDecoder("utf-8").decode(value);
            buffer += text;
            
            contentElement.innerHTML = buffer.replace(/(\r\n|\n|\r)/gm, "<br>");
            chatWindow.scrollTop = chatWindow.scrollHeight;
            resetTimer();
            // Process the next chunk of text
            reader.read().then(processText);
          });
        }
      )
        .catch(error => {
        const errorMessage = document.createElement('div');
        errorMessage.classList.add('error-message');
        errorMessage.textContent = '连接已断开，请检查网络连接后重新尝试。';
        clearTimeout(timerId);
        chatWindow.appendChild(errorMessage);
        chatWindow.scrollTop = chatWindow.scrollHeight;
        enableInput();
        
        function handleMediaChange2(e) {
                if (e.matches) {
                  
                  messageInput.blur();
                  messageInput.style.height = "auto";
                  messageInput.style.height = "130px";
                  chatWindow.style.height = "calc(100vh - 130px)";
                } else {
                  messageInput.focus();
                }
              }
              
          mediaQuery.addListener(handleMediaChange2);
          handleMediaChange2(mediaQuery);
        });
      }
    }
    </script>
  </body>
</html>
